VB6 Static Class Variables (Sort Of)

Mark Leighton Fisher on 2006-06-09T16:09:44

You can't really have static class variables in VB6, but you can simulate it. Here's how.

The trick is to use a Public Static Function in a plain old module (not a Class). The function acts as an accessor to its static datum:

Public Static Function AssertTests(newValue As Long, setValue As Boolean) As Long

    On Error GoTo AssertTests_Error
    
    Dim testsValue As Long
    
    If setValue Then
        testsValue = newValue
    End If
    
    AssertTests = testsValue
    
    Exit Function
    
AssertTests_Error:

    Err.Raise Err.Number, Err.Source, "AssertTests: " & Err.Description
    
End Function

AssertTests(newValue, setValue) acts as a gatekeeper to the actual static variable. If you happen to have a way to further control the data access like caller() in Perl:

package main;

zoe();

xjoe::joey();

exit(0);


sub zoe {
    my @frame = caller();
    print "called from '", $frame[0], "'\n";
}

package xjoe;

sub joey {
    joe();
}

sub joe {
    my @frame = caller();
    if ($frame[0] ne "joe") {
        die "Only 'joe' objects can call me, bucky!\n";
    }
    print "called from '", $frame[0], "'\n";
}

then you can block the execution of the gatekeeper from any class except the one that you want. Implementing caller() in VB6 looks possible in debugging code, using the dbghelp.dll API. (VB.NET has better support for caller(), of course, as well as static class variables.)

You can then wrap these gatekeepers in VB6 Properties, so they look like the long-desired static class variables:

Private Property Get Tests() As Long

    On Error GoTo Get_Tests_Error
    
    Tests = AssertTests(0, False)
    
Get_Tests_Exit:

    Exit Property
    
Get_Tests_Error:

    Err.Raise Err.Number, Err.Source, "Tests-GET: " & Err.Description
    
End Property

Private Property Let Tests(vData As Long)

    On Error GoTo Let_Tests_Error
    
    AssertTests vData, True

Let_Tests_Exit:

    Exit Property
    
Let_Tests_Error:

    Err.Raise Err.Number, Err.Source, "Tests-LET: " &Err.Description
    
End Property

FWIW, VB6 static class variables are part of trying to develop VB6Unit, an Open Source VSTS-compatible unit testing framework for VB6. I make no promises about when, if ever, VB6Unit actually sees the light of day.